package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    /**
     * 1.通过用户查询用户和密码信息（已加密）
     * 2.定义集合封装权限
     * 3.给框架返回该用户
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //获取用户及其密码
        User user = userService.findByUsername(username);
        String password = user.getPassword();

        List<GrantedAuthority> list = new ArrayList<>();

        //获取该用户的所有角色权限，这些权限是平行关系
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            //添加角色关键字，用于权限控制
            list.add(new SimpleGrantedAuthority(role.getKeyword()));

            //透过角色获取所有权限
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //添加权限关键字，用于权限控制
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        return new org.springframework.security.core.userdetails.User(username, password, list);
    }
}
